package com.example.xmpic.ui.utils;

import com.example.xmpic.ui.data.CameraLocalFile;
import com.example.xmpic.ui.data.CameraLocalFileDao;

import java.util.List;

/**
 * @author skygge
 * @date 2020/7/20.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class CameraFileUtil {

    private volatile static CameraFileUtil instance = null;
    private CameraLocalFileDao mCameraDao;

    public static CameraFileUtil getInstance() {
        if (instance == null){
            synchronized (CameraFileUtil.class){
                if (instance == null){
                    instance = new CameraFileUtil();
                }
            }
        }
        return instance;
    }

    private CameraFileUtil() {
        mCameraDao = FunSdkInitUtil.getInstance().getDaoSession().getCameraLocalFileDao();
    }

    /**
     * 插入数据
     */
    public void insertLocalFile(CameraLocalFile file){
        mCameraDao.insertOrReplace(file);
    }

    /**
     * 更新数据
     */
    public void updateLocalFile(CameraLocalFile file){
        mCameraDao.update(file);
    }

    /**
     * 更新数据
     */
    public void updateLocalFile(List<CameraLocalFile> files, String deviceSn){
        List<CameraLocalFile> mLocal = findCameraDownload(deviceSn);
        if (mLocal.size()>0){
            for (int i = 0; i < mLocal.size(); i++) {
                CameraLocalFile localFile = mLocal.get(i);
                for (int j = 0; j < files.size(); j++) {
                    CameraLocalFile local = files.get(j);
                    if (localFile.getDownTime().equals(local.getDownTime())){
                        localFile = local;
                        mCameraDao.update(localFile);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 通过序列号查询
     */
    public List<CameraLocalFile> findCameraDownload(String deviceSn){
        return mCameraDao.queryBuilder().where(CameraLocalFileDao.Properties.Serial.eq(deviceSn))
                .orderAsc(CameraLocalFileDao.Properties.DownTime)
                .build()
                .list();
    }

    /**
     * 查询本地文件
     */
    public CameraLocalFile findCameraFile(String downTime, String deviceSn){
        return mCameraDao.queryBuilder()
                .where(CameraLocalFileDao.Properties.Serial.eq(deviceSn),
                        CameraLocalFileDao.Properties.DownTime.eq(downTime))
                .build()
                .unique();
    }

    /**
     * 根据下载时间删除
     */
    public void deleteByDownTime(String downTime){
        mCameraDao.queryBuilder()
                .where(CameraLocalFileDao.Properties.DownTime.eq(downTime))
                .buildDelete()
                .executeDeleteWithoutDetachingEntities();
    }

    /**
     * 清空所有数据
     */
    public void deleteAllLocalFile(){
        mCameraDao.deleteAll();
    }
}
